package video

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/utils"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/frame/g"
)

// SaveLabels 保存视频标签值
func (v *sVideo) SaveLabels(ctx context.Context, videoId uint, values ...string) error {
	if len(values) == 0 {
		return exception.New(`视频标签不能为空`)
	}

	// 初始化
	var (
		where = g.Map{
			dao.VideoLabel.Columns().VideoId: videoId,
		}
		labels           = make([]model.VideoLabelItem, 0)
		valuesExistsBool = make(map[string]bool)
	)

	// 清理之前标签值
	if b, _ := v.LabelModel().Exists(ctx, where); b {
		err := v.LabelModel().Delete(ctx, where)
		if err != nil {
			return exception.New(`清理视频历史标签失败，请重试`)
		}
	}

	// 迭代处理数据
	for _, value := range values {
		// 是否重复
		if _, ok := valuesExistsBool[value]; ok {
			continue
		}
		labels = append(labels, model.VideoLabelItem{
			VideoId: videoId,
			Value:   value,
		})
		valuesExistsBool[value] = true
	}

	// 添加数据
	err := v.LabelModel().Save(ctx, labels)
	if err != nil {
		return exception.New(`保存视频标签值失败`)
	}
	return nil
}

// GetVideoIdByValue 通过标签值获取视频ID
func (v *sVideo) GetVideoIdByValue(ctx context.Context, values ...string) ([]uint, error) {
	if len(values) == 0 {
		return nil, exception.New(`视频标签值不能为空`)
	}
	var labels []model.VideoLabelItem
	if err := v.LabelModel().Scan(ctx, g.Map{
		dao.VideoLabel.Columns().Value: values,
	}, &labels); err != nil {
		return nil, err
	}

	// 标签值不存在
	if len(labels) == 0 {
		return nil, exception.New(`视频标签值不存在`)
	}
	return utils.NewArray(labels).Units(dao.VideoLabel.Columns().VideoId), nil
}

// GetLabelValueList 通过视频ID获取视频标签值列表
func (v *sVideo) GetLabelValueList(ctx context.Context, videoId uint) ([]model.VideoLabelItem, error) {
	var values []model.VideoLabelItem
	// 获取标签值列表
	if err := v.LabelModel().Scan(ctx, g.Map{
		dao.VideoLabel.Columns().VideoId: videoId,
	}, &values); err != nil {
		return nil, exception.New(`视频标签不存在`)
	}
	return values, nil
}

// deleteLabelByVideoId 通过视频ID删除视频标签
func (v *sVideo) deleteLabelByVideoId(ctx context.Context, videoId uint) error {
	where := g.Map{
		dao.VideoLabel.Columns().VideoId: videoId,
	}
	if b, _ := v.LabelModel().Exists(ctx, where); !b {
		return nil
	}

	// 删除数据
	return v.LabelModel().Delete(ctx, where)
}
